"""
语音提醒模块
用于在安全验证时播放语音提醒
"""
import threading
import pyttsx3


class VoiceReminder:
    """语音提醒类"""
    
    def __init__(self, logger=None):
        """
        初始化语音提醒器
        
        Args:
            logger: 日志记录器实例
        """
        self.logger = logger
        self.current_engine = None  # 当前播放的引擎实例
        self.is_playing = False  # 是否正在播放
    
    def _configure_engine(self, engine):
        """配置语音引擎参数"""
        engine.setProperty('rate', 150)  # 语速：每分钟150词
        engine.setProperty('volume', 1)  # 音量：100%
        
        # 尝试设置中文语音（如果系统支持）
        voices = engine.getProperty('voices')
        for voice in voices:
            if 'chinese' in voice.name.lower() or 'zh' in voice.id.lower():
                engine.setProperty('voice', voice.id)
                break
    
    def play_security_alert(self):
        """播放安全验证提醒"""
        # 如果已经在播放，先停止
        if self.is_playing:
            self.stop_voice()
        
        text = "猪猪侠提醒您，需要进行安全验证，请完成安全验证，保证程序正常运行！"
        self.is_playing = True
        self._play_voice_async(text)
        
        if self.logger:
            self.logger.info("播放安全验证语音提醒")
    
    def _play_voice_async(self, text):
        """异步播放语音，避免阻塞界面"""
        def play():
            try:
                # 创建独立的引擎实例
                local_engine = pyttsx3.init()
                self.current_engine = local_engine
                
                # 配置引擎参数
                self._configure_engine(local_engine)
                
                # 播放语音
                local_engine.say(text)
                local_engine.runAndWait()
                
                # 播放完成，重置状态
                self._reset_state()
                
                if self.logger:
                    self.logger.debug("语音播放完成")
            except Exception as e:
                # 播放出错，重置状态
                self._reset_state()
                if self.logger:
                    self.logger.error(f"语音播放失败: {e}")
        
        thread = threading.Thread(target=play, daemon=False)
        thread.start()
    
    def stop_voice(self):
        """停止语音播放"""
        if not self.is_playing:
            return
        
        try:
            if self.current_engine:
                self.current_engine.stop()
                if self.logger:
                    self.logger.info("语音播放已停止")
        except Exception as e:
            if self.logger:
                self.logger.error(f"停止语音播放时出错: {e}")
        finally:
            self._reset_state()
    
    def _reset_state(self):
        """重置播放状态"""
        self.is_playing = False
        self.current_engine = None
